package com.ukefu.webim.service.impl;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.ukefu.util.UKTools;
import com.ukefu.util.mail.Mail;
import com.ukefu.webim.service.es.ContactsRepository;
import com.ukefu.webim.service.es.OrdersCommentRepository;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.service.repository.WorkOrderTypeRepository;
import com.ukefu.webim.web.model.OrdersComment;
import com.ukefu.webim.web.model.SystemConfig;
import com.ukefu.webim.web.model.Template;
import com.ukefu.webim.web.model.UKeFuDic;
import com.ukefu.webim.web.model.User;
import com.ukefu.webim.web.model.WorkOrders;

import freemarker.template.TemplateException;

@Service("workorderssendmail")
public class WorkOrdersSendMailService {
	@Autowired
	private UserRepository userRes ;
	@Autowired
	private WorkOrderTypeRepository workOrderTypeRes ;
	@Autowired
	private OrdersCommentRepository ordersCommentRes ;
	@Autowired
	private ContactsRepository contactsRes ;
	
	/**
	 * 创建工单的时候，发送给发起人和受理人的邮件模板
	 * @throws TemplateException 
	 * @throws IOException 
	 */
	public void sendCreateWorkOrdersMail(WorkOrders workOrders,User creater,String Orgi) throws IOException, TemplateException {
		SystemConfig systemConfig = UKTools.getSystemConfig();
    	if(systemConfig!=null&&systemConfig.isEnablemail()&&!StringUtils.isBlank(systemConfig.getMailcreatetp())) {
			Map<String,Object> tplValuesMap = getDataMap(workOrders, creater, Orgi);
    		Template tp = UKTools.getTemplate(systemConfig.getMailcreatetp()) ;
			String content = UKTools.getTemplet(tp.getTemplettext(),tplValuesMap) ;
			String subject = StringUtils.isBlank(tp.getTemplettitle())?"":UKTools.getTemplet(tp.getTemplettitle(),tplValuesMap) ;
			User initiator = (User)tplValuesMap.get("initiator");
			User current = (User)tplValuesMap.get("current");
			Boolean isShowName = systemConfig.isEmailshowrecipient();
			//当前发起人
			if(initiator!=null) {
				Mail initiatorMail = new Mail(getEmailName(isShowName, initiator.getEmail(), initiator.getUname()),subject,content);
				UKTools.published(initiatorMail);
			}
			//当前受理人
			if(current!=null) {
				Mail currentMail = new Mail(getEmailName(isShowName, current.getEmail(), current.getUname()),subject,content);
				UKTools.published(currentMail);
			}
			/*if(systemConfig.isEmailtocreater()) {
				//发送给创建人生效 以及创建人不为发起人和不为受理人时发送
				if((!StringUtils.isBlank(workOrders.getInitiator())&&!workOrders.getInitiator().equals(creater.getId()))&&(current!=null&&!current.getId().equals(creater.getId()))) {
					UKTools.published( getEmailName(isShowName, creater.getEmail(), creater.getUname()),subject,content));
				}
			}*/
			
		}
	}
	
	/**
	 * 工单状态改变的时候，发送给发起人和受理人的邮件模板
	 * @throws TemplateException 
	 * @throws IOException 
	 */
	public void sendUpdateWorkOrdersMail(WorkOrders workOrders) throws IOException, TemplateException {
		SystemConfig systemConfig = UKTools.getSystemConfig();
    	if(systemConfig!=null&&systemConfig.isEnablemail()&&!StringUtils.isBlank(systemConfig.getMailupdatetp())) {
    		User creater = userRes.findByIdAndOrgi(workOrders.getCreater(),systemConfig.getOrgi());
    		String Orgi = workOrders.getOrgi();
    		Map<String,Object> tplValuesMap = getDataMap(workOrders, creater, Orgi);
    		Template tp = UKTools.getTemplate(systemConfig.getMailupdatetp()) ;
			String content = UKTools.getTemplet(tp.getTemplettext(),tplValuesMap) ;
			String subject = StringUtils.isBlank(tp.getTemplettitle())?"":UKTools.getTemplet(tp.getTemplettitle(),tplValuesMap) ;
			User initiator = (User)tplValuesMap.get("initiator");
			User current = (User)tplValuesMap.get("current");
			Boolean isShowName = systemConfig.isEmailshowrecipient();
			//当前发起人
			if(initiator!=null) {
				Mail initiatorMail = new Mail(getEmailName(isShowName, initiator.getEmail(), initiator.getUname()),subject,content);
				UKTools.published(initiatorMail);
			}
			//当前受理人
			if(current!=null) {
				Mail currentMail = new Mail(getEmailName(isShowName, current.getEmail(), current.getUname()),subject,content);
				UKTools.published(currentMail);
			}
			if(systemConfig.isEmailtocreater()) {
				//发送给创建人生效 以及创建人不为发起人和不为受理人时发送
				if((!StringUtils.isBlank(workOrders.getInitiator())&&!workOrders.getInitiator().equals(creater.getId()))&&(current!=null&&!current.getId().equals(creater.getId()))) {
					Template tpToCreater = UKTools.getTemplate(systemConfig.getEmailtocreatertp()) ;
					String contentForCreater = UKTools.getTemplet(tpToCreater.getTemplettext(),tplValuesMap) ;
					String subjectForCreater = UKTools.getTemplet(tpToCreater.getName(),tplValuesMap) ;
					UKTools.published( new Mail(getEmailName(isShowName, creater.getEmail(), creater.getUname()),subjectForCreater,contentForCreater));
				}
			}
			
		}
	}
	 public Page<OrdersComment> getCommentList(WorkOrders workOrders , String orgi ){
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
    	myBuilder.must(termQuery("dataid" , workOrders.getId())) ;
    	myBuilder.must(termQuery("orgi" , orgi)) ;
    	boolQueryBuilder.must(myBuilder) ;
    	return ordersCommentRes.findByQuery(boolQueryBuilder, null , new PageRequest(0,10000 , Direction.DESC , "createtime"));
    }
	private Map<String,Object> getDataMap(WorkOrders workOrders,User creater,String Orgi) {
		Map<String,Object> tplValuesMap = new HashMap<String,Object>();
		if(!StringUtils.isBlank(workOrders.getCusid())){
			workOrders.setContacts(contactsRes.findByIdAndOrgi(workOrders.getCusid(),Orgi));
		}
		tplValuesMap.put("workOrders", workOrders);//
		tplValuesMap.put("workOrderTypeList", workOrderTypeRes.findByOrgi(Orgi)) ;//工单类型
		User initiator = null;
		User current = null;
		if(!StringUtils.isBlank(workOrders.getInitiator())){
			initiator =  userRes.findByIdAndOrgi(workOrders.getInitiator(),Orgi);
			tplValuesMap.put("initiator",initiator);
		}
		if(!StringUtils.isBlank(workOrders.getAccuser())){
			current = userRes.findByIdAndOrgi(workOrders.getAccuser(),Orgi);
			workOrders.setCurrent(current);
			tplValuesMap.put("current",workOrders.getCurrent());//当前处理人
		}
		tplValuesMap.put("creater", creater);//创建人
		tplValuesMap.put("uKeFuDic", UKeFuDic.getInstance());
		tplValuesMap.put("commentList", getCommentList(workOrders, Orgi).getContent()) ;//工单类型
		return tplValuesMap;
	}
	
	private String getEmailName(Boolean isShowName,String email,String name) {
		if(isShowName) {
			return name+" <"+email+">";
		}
		return email;
	}
}
